package com.mylock;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

/**
 * @author:wesley
 */
public class MyLockWatch implements Watcher {

    private MyDistributedLock lock;

    private MyDoTemplate template;


    public MyLockWatch(MyDistributedLock lock, MyDoTemplate template) {
        this.lock = lock;
        this.template = template;
    }

    public void process(WatchedEvent watchedEvent) {

        //之前等待节点已经删除
        if (watchedEvent.getType() == Event.EventType.NodeDeleted &&
                watchedEvent.getPath().equals(lock.getWaitPath())) {
            try {
                if (lock.isMinPath()) {
                    doSomething();
                    lock.unLock();
                }
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void doSomething() {
        System.out.println(Thread.currentThread().getName() + "已经获取锁了。。。。。");
        MyMainTest.threadCdl.countDown();
        template.doSomeThing();
    }

}
